package com.mingqijia.gassafety.shared.user;

import cn.hutool.json.JSONObject;
import com.gap.basic.exception.BizException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;

/**
 * 获取当前用户
 * @author damon
 */
public interface UserFactory {

    /** 获取当前用户 */
    UserBackend getPrincipal();

    /** 获取附属参数 */
    default JSONObject getObject() {
        Authentication authentication = getAuthentication();
        if (authentication.getCredentials() instanceof JSONObject) {
            return (JSONObject) authentication.getCredentials();
        }
        return null;
    }

    default Authentication getAuthentication() {
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        if (ObjectUtils.isEmpty(authentication)) {
            throw new BizException("用户未登录");
        }
        return authentication;
    }
}
